package com.zeratul.common.feign.config;

import com.zeratul.common.core.factory.YmlPropertySourceFactory;
import com.zeratul.common.feign.config.prop.ZeratulFeignProperties;
import com.zeratul.common.feign.inter.ContextFeignReqInterceptor;
import com.zeratul.common.feign.inter.SaTokenFeignReqInterceptor;
import com.zeratul.common.feign.inter.web.FeignServerInterceptor;
import com.zeratul.common.satoken.config.ZeratulSaTokenAutoConfiguration;
import com.zeratul.web.interceptor.base.BaseHandlerInterceptor;
import feign.RequestInterceptor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;

@AutoConfiguration(afterName = "com.zeratul.common.satoken.config.ZeratulSaTokenAutoConfiguration")
@PropertySource(value = "classpath:common-feign.yml", factory = YmlPropertySourceFactory.class)
@EnableConfigurationProperties(ZeratulFeignProperties.class)
/**
 * 启动Feign注解，扫描指定包下的Feign接口，扫描路径可配置
 */
@EnableFeignClients(basePackages = "${feign.base-packages}")
public class ZeratulFeignAutoConfiguration {

    /**
     * Feign被调用端拦截器
     */
    @Bean
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
    public BaseHandlerInterceptor feignServerInterceptor() {
        return new FeignServerInterceptor();
    }

    /**
     * Feign调用端拦截器 - 上下文数据传递
     */
    @Bean
    public RequestInterceptor contextFeignReqInterceptor() {
        return new ContextFeignReqInterceptor();
    }

    /**
     * Feign调用端拦截器
     */
    @Bean
    @ConditionalOnBean(ZeratulSaTokenAutoConfiguration.class)
    public RequestInterceptor saTokenFeignReqInterceptor() {
        return new SaTokenFeignReqInterceptor();
    }
}
